package com.pangu.core.engine.game.action.zhajinhua;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheConfigTools;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.task.zhajinhua.CreateZhajinhuaAITask;
import com.pangu.core.statemachine.action.Action;
import com.pangu.core.statemachine.impl.BeiMiExtentionTransitionConfigurer;
import com.pangu.core.statemachine.message.Message;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.SysGameConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Description:进入房间，并且开始初始化ai机器人进入房间
 *
 * @author abo
 * @date 2018年4月16日
 * @param <T>
 * @param <S>
 */
@Slf4j
public class ZhajinhuaEnterAction<T, S> implements Action<T, S> {

	/**
	 * 进入房间后召唤机器人， 撮合成功的，立即开启游戏
	 */
	@Override
	public void execute(Message<T> message, BeiMiExtentionTransitionConfigurer<T, S> configurer) {
		String roomId = (String) message.getMessageHeaders().getHeaders().get("room");
		if (!StringUtils.isBlank(roomId)) {
			GameRoom gameRoom = (GameRoom) CacheHelper.getGameRoomCacheBean().getCacheObject(roomId,
					BMDataContext.SYSTEM_ORGI);
			Collection list = CacheHelper.getGameRoomCacheBean().getAllCacheObject("orgi");
			if (gameRoom != null) {
				boolean flag = BMDataContext.getZhajinhuaEngine().isHaveNormalPlayerInGameRoom(roomId);
				log.info("------------------进行房间在线玩家检查，当前房间" + roomId + "是否还有真人，true还有真人，false没有真人：" + flag);
				// 判断当前房间里面还有没有在线的真人玩家。
				if (flag) {
					// AiConfig aiConfig = CacheConfigTools.getAiConfig(gameRoom.getOrgi());
					SysGameConfig gameConfig = CacheConfigTools.getSysGameConfig(gameRoom.getOrgi());
					if (gameConfig.isEnableai()) {
						// 获取到传过来的定时器的间隔时间
						int interval = (int) message.getMessageHeaders().getHeaders().get("interval");
						CacheHelper.getExpireCache().put(gameRoom.getOrgi(),
								new CreateZhajinhuaAITask(interval, gameRoom, gameRoom.getOrgi()));
					}
					// 更新状态
					gameRoom.setStatus(configurer.getTarget().toString());
					// 初始化好房间后放入缓存
					CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, gameRoom.getOrgi());
				} else {
					BMDataContext.getZhajinhuaEngine().dismissRoom(gameRoom, BMDataContext.SYSTEM_ORGI);
				}
			}
		}
	}
}
